package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.SpinnerAdapter
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.databinding.FragmentDeviceManageBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.DeviceManageContract
import com.sy.simpleegg.mvp.presenter.DeviceManagePresenter
import com.sy.simpleegg.util.Preference
import com.sy.simpleegg.util.SPHelper
import com.sy.logger.Logger

class DeviceManageFragment :
    BaseMvpFragment<DeviceManageContract.View, DeviceManageContract.Presenter, FragmentDeviceManageBinding>(),
    DeviceManageContract.View {

    private var controlType = 0
    private var platformType = 0
    private var data: Array<String>? = null
    private var platform: Array<String>? = null

    private var coinEnable = "11"
    private var banknoteEnable = "11"
    private var backscanEnable = "1"

    companion object {
        fun getInstance(): DeviceManageFragment = DeviceManageFragment()
    }

    /**
     * 设备编号
     */
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")

    override fun createPresenter(): DeviceManageContract.Presenter =
        DeviceManagePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_device_manage

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = false
        isCountDownBackHome = false
    }

    override fun initView(view: View) {
        super.initView(view)

        data = arrayOf(getString(R.string.control_type_self), getString(R.string.control_type_lyy), getString(R.string.control_type_fix))
        platform = arrayOf(
            getString(R.string.control_type_self),
            getString(R.string.control_type_lyy_sdk),
            getString(R.string.control_type_lyy_box)
        )

        binding.etCustomer.setText(SPHelper.getSL())

        binding.btnSaveDevice.setOnClickListener {
            if (!isFirstClick()){
                return@setOnClickListener
            }
            saveSetting()
        }

        setSpinner()

        setCheckBoxState()

        setSwitchState()

//        binding.rlTouch.setTouchListener(object : TouchRelativeLayout.TouchListener {
//            override fun touch() {
//                startCountDown()
//            }
//        })
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentDeviceManageBinding {
        return FragmentDeviceManageBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    private fun setSpinner(){
        try {
            binding.spControlType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                    if (position == controlType) {
                        return
                    }
                    SPHelper.setControlType(position)
                    logFile("选中控制板类型：${data?.get(position)}")
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                    TODO("Not yet implemented")
                }
            }
            binding.spPlatformType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                    if (position == platformType) {
                        return
                    }
                    SPHelper.setAccessPlatform(position)
                    logFile("选中平台类型：${platform?.get(position)}")
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                    TODO("Not yet implemented")
                }
            }

            controlType = SPHelper.getControlType()
            binding.spControlType.adapter = SpinnerAdapter(data!!)
            binding.spControlType.setSelection(controlType)

            platformType = SPHelper.getAccessPlatform()
            binding.spPlatformType.adapter = SpinnerAdapter(platform!!)
            binding.spPlatformType.setSelection(platformType)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("设置Spinner数据异常：" + e.message)
        }
    }

    private fun setCheckBoxState() {
        try {
            val denomination1 = SPHelper.getBanknoteDenomination1().toCharArray()
            binding.cb11.isChecked = (denomination1[0] == '1')
            binding.cb15.isChecked = (denomination1[1] == '1')
            binding.cb110.isChecked = (denomination1[2] == '1')
            binding.cb120.isChecked = (denomination1[3] == '1')
            binding.cb150.isChecked = (denomination1[4] == '1')
            binding.cb1100.isChecked = (denomination1[5] == '1')
        }catch (e: Exception){
            e.printStackTrace()
            logFile("设置Checkbox数据异常：" + e.message)
        }
    }

    private fun setSwitchState() {
        try {
            coinEnable = SPHelper.getCoinEnable()
            binding.switchCoin1.isChecked = (coinEnable[0] == '1')
            binding.switchCoin2.isChecked = (coinEnable[1] == '1')
            banknoteEnable = SPHelper.getBanknoteEnable()
            binding.switchBanknote1.isChecked = (banknoteEnable[0] == '1')
            backscanEnable = SPHelper.getBackscanEnable()
            binding.switchBackscan.isChecked = (backscanEnable[0] == '1')
        }catch (e: Exception){
            e.printStackTrace()
            logFile("设置Switch数据异常：" + e.message)
        }
    }

    private fun saveSetting(){
        try {
            val customerStr = binding.etCustomer.text.toString()
            if (customerStr.isNotEmpty()) {
                var isChange = false
                SPHelper.setSL(customerStr)
                //保存面额启用状态
                val denomination1 = getDenomination()
                SPHelper.setBanknoteDenomination1(denomination1)

                //保存纸币机启用状态
                val banknote = getBanknote()
                if (banknoteEnable != banknote) {
                    isChange = true
                }
                SPHelper.setBanknoteEnable(banknote)

                //保存投币机启用状态
                val coin = getCoin()
                if (coinEnable != coin) {
                    isChange = true
                }
                SPHelper.setCoinEnable(coin)

                //保存反扫器启用状态
                val backscan = getBackscan()
                if (backscanEnable != backscan) {
                    isChange = true
                }
                SPHelper.setBackscanEnable(backscan)
                if (isChange) {
                    showToastMsg(getString(R.string.save_success_reboot))
                } else {
                    showToastMsg(getString(R.string.save_success))
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Logger.e("DeviceManageFragment 保存数据异常：" + e.message)
        }
    }

    private fun getDenomination(): String? {
        var d = ""
        try {
            d += if (binding.cb11.isChecked) 1 else 0
            d += if (binding.cb15.isChecked) 1 else 0
            d += if (binding.cb110.isChecked) 1 else 0
            d += if (binding.cb120.isChecked) 1 else 0
            d += if (binding.cb150.isChecked) 1 else 0
            d += if (binding.cb1100.isChecked) 1 else 0
        }catch (e: Exception){
            e.printStackTrace()
            logFile("getDenomination()异常：${e.message}")
        }
        return d
    }

    private fun getBanknote(): String? {
        var s = ""
        s += if (binding.switchBanknote1.isChecked) 1 else 0
        return s
    }

    private fun getCoin(): String? {
        var s = ""
        s += if (binding.switchCoin1.isChecked) 1 else 0
        s += if (binding.switchCoin2.isChecked) 1 else 0
        return s
    }

    private fun getBackscan(): String? {
        var s = ""
        s += if (binding.switchBackscan.isChecked) 1 else 0
        return s
    }
}